const fs = require('fs')
const url = require('url')
const path = require('path')
const mime = require('mime')

function handleError(err, req, res) {
    if (err.code && err.code == 'ENOENT') {
        res.statusCode = '404'
        res.end('not found')
    } else {
        res.statusCode = '500'
        res.end('inner error')
    }
}
function handleResponse(data, req, res, pathname) {
    res.setHeader('content-type', mime.getType(pathname))
    res.end(data)
}

function send(root, options) {
    options = Object.assign({
        handleError,
        handleResponse
    }, options || {})
    return function (req, res) {
        const pathname = path.resolve(root, getPathname(req))
        fs.readFile(pathname, {
            encoding: 'utf-8'
        }, function (err, data) {
            if (err) {
                options.handleError(err, req, res)
            } else {
                options.handleResponse(data, req, res, pathname)
            }
        })
    }
}

function getPathname(req) {
    const pathname = '.' + url.parse(req.url).pathname
    return pathname == './' ? './index.html' : pathname
}
send.handleError = handleError
send.handleResponse = handleResponse
module.exports = send